"use strict";

var http = require('http');

// 模拟浏览器
var opt = {
    method: "GET",
    host: "s1.dfcfw.com",
    // port: 8080,
    // path: "/xml/index.xml?rt=" + Math.floor((new Date().getTime()) / 30000),
    headers: {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, sdch",
        "Accept-Language": "zh-CN,zh;q=0.8",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Host": "s1.dfcfw.com",
        "Pragma": "no-cache",
        "Referer": "http://data.eastmoney.com/zjlx/dpzjlx.html",
        "User-Agent": agents[Math.floor(Math.random() * agents.length)],
        "X-Requested-With": flash[Math.floor(Math.random() * flash.length)]
    }
};

function handleRequest(req, res) {

    if (req.params.id === 'now') {
        opt.path = "/xml/index.xml?rt=" + new Date().getTime();
    }
    if (req.params.id === 'all') {
        opt.path = "/allXML/index.xml?rt=" + Math.floor((new Date().getTime() - 24 * 60 * 60 * 1000) / 30000);
    }

    var result = '';
    var contentType;

    var serverReq = http.request(opt, function (serverData) {
        // console.log(`STATUS: ${serverData.statusCode}`);
        // console.log(`HEADERS: ${JSON.stringify(serverData.headers)}`);

        contentType = serverData.headers["content-type"];
        serverData.setEncoding('utf8');
        serverData.on('data', chunk => {
            result += chunk;
            // console.log(chunk)
            // console.log(`BODY: ${chunk}`);
        });
        serverData.on('end', () => {
            res.type('text/plain'); //serverData.headers["content-type"]
            res.send(result);
            // console.log('No more data in response.')
        });
    });

    serverReq.on('error', e => {
        console.log(`problem with request: ${e.message}`);
    });

    serverReq.write("\n");
    serverReq.end();
}